#!/bin/bash
###############################################################################
#       脚本名称: formatter_plain.sh
#       功能描述: 纯文本格式化器,将日志事件格式化为可读的纯文本
#       作者: 林再来
#       日期: 2025-10-14
#       版本: 1.0
#       功能:
#           1、支持模板变量替换(%datetime、%level、%message等)
#           2、支持自定义时间格式
#           3、支持颜色输出(可选)
#           4、高性能字符串处理
#       依赖(插件/命令):
#           date
###############################################################################

# 防止重复加载
[[ -n "${_FORMATTER_PLAIN_LOADED:-}" ]] && return 0
readonly _FORMATTER_PLAIN_LOADED=1

# 加载日志级别模块
_FORMATTER_PLAIN_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${_FORMATTER_PLAIN_DIR}/../core/log_level.sh"

#-----------------------------------------------------------------------------
# 默认格式模板（参考config模块的做法，先检查是否已定义）
#-----------------------------------------------------------------------------
if [[ -z "${DEFAULT_PLAIN_PATTERN:-}" ]]; then
    readonly DEFAULT_PLAIN_PATTERN="[%level] %datetime - %message"
fi
if [[ -z "${DEFAULT_DATETIME_FORMAT:-}" ]]; then
    readonly DEFAULT_DATETIME_FORMAT="%Y-%m-%d %H:%M:%S"
fi

#-----------------------------------------------------------------------------
# 函数: 格式化日志事件为纯文本
# 参数: $1 - 事件JSON字符串
#       $2 - 格式模板(可选,默认使用DEFAULT_PLAIN_PATTERN)
#       $3 - 是否启用颜色(true/false,可选,默认false)
# 返回: 输出格式化后的纯文本
#-----------------------------------------------------------------------------
function _formatter_plain_format() {
    local event="$1"
    local pattern="${2:-$DEFAULT_PLAIN_PATTERN}"
    local enable_color="${3:-false}"
    
    # 从JSON事件中提取字段(使用简单的文本处理,避免依赖jq)
    local timestamp level message module script line function_name trace_id hostname username pid
    
    timestamp=$(echo "$event" | grep -oP '(?<="timestamp":")[^"]*' || echo "")
    level=$(echo "$event" | grep -oP '(?<="level":")[^"]*' || echo "")
    message=$(echo "$event" | grep -oP '(?<="message":")[^"]*' || echo "")
    module=$(echo "$event" | grep -oP '(?<="module":")[^"]*' || echo "")
    script=$(echo "$event" | grep -oP '(?<="script":")[^"]*' || echo "")
    line=$(echo "$event" | grep -oP '(?<="line":")[^"]*' || echo "")
    function_name=$(echo "$event" | grep -oP '(?<="function":")[^"]*' || echo "")
    trace_id=$(echo "$event" | grep -oP '(?<="trace_id":")[^"]*' || echo "")
    hostname=$(echo "$event" | grep -oP '(?<="hostname":")[^"]*' || echo "")
    username=$(echo "$event" | grep -oP '(?<="username":")[^"]*' || echo "")
    pid=$(echo "$event" | grep -oP '(?<="pid":")[^"]*' || echo "")
    
    # 格式化时间戳
    local formatted_time="$timestamp"
    
    # 替换模板变量
    local output="$pattern"
    output="${output//%datetime/$formatted_time}"
    output="${output//%level/$level}"
    output="${output//%message/$message}"
    output="${output//%module/$module}"
    output="${output//%script/$script}"
    output="${output//%line/$line}"
    output="${output//%function/$function_name}"
    output="${output//%trace_id/$trace_id}"
    output="${output//%hostname/$hostname}"
    output="${output//%username/$username}"
    output="${output//%pid/$pid}"
    
    # 添加颜色(如果启用)
    if [[ "$enable_color" == "true" ]] && [[ -n "$level" ]]; then
        local color=$(_log_level_get_color "$level")
        local reset="$COLOR_RESET"
        echo -e "${color}${output}${reset}"
    else
        echo "$output"
    fi
}

#-----------------------------------------------------------------------------
# 函数: 使用扩展模板格式化
# 参数: $1 - 事件JSON字符串
#       $2 - 格式化器名称(用于获取配置)
# 返回: 输出格式化后的文本
#-----------------------------------------------------------------------------
function formatter_plain_format() {
    local event="$1"
    local formatter_name="${2:-plain}"
    
    # TODO: 从配置中获取pattern和color设置
    # 当前使用默认值
    local pattern="$DEFAULT_PLAIN_PATTERN"
    local enable_color="false"
    
    _formatter_plain_format "$event" "$pattern" "$enable_color"
}

#-----------------------------------------------------------------------------
# 函数: 从配置创建格式模板
# 参数: $1 - 自定义模板
#       $2 - 时间格式
# 返回: 输出格式字符串
#-----------------------------------------------------------------------------
function _formatter_plain_build_pattern() {
    local custom_pattern="$1"
    local datetime_format="${2:-$DEFAULT_DATETIME_FORMAT}"
    
    # 如果提供了自定义模板,使用自定义模板
    if [[ -n "$custom_pattern" ]]; then
        echo "$custom_pattern"
    else
        echo "$DEFAULT_PLAIN_PATTERN"
    fi
}

#-----------------------------------------------------------------------------
# 测试函数
#-----------------------------------------------------------------------------
function _formatter_plain_test() {
    echo "=== 纯文本格式化器测试 ==="
    
    # 构造测试事件
    local test_event
    test_event=$(cat <<'EOF'
{
    "timestamp": "2025-10-14 15:30:45",
    "level": "INFO",
    "message": "用户登录成功",
    "module": "auth",
    "script": "login.sh",
    "line": "123",
    "function": "do_login",
    "trace_id": "req-12345",
    "hostname": "server01",
    "username": "admin",
    "pid": "9876"
}
EOF
)
    
    echo "1. 默认格式测试:"
    _formatter_plain_format "$test_event"
    
    echo ""
    echo "2. 带颜色格式测试:"
    _formatter_plain_format "$test_event" "$DEFAULT_PLAIN_PATTERN" "true"
    
    echo ""
    echo "3. 自定义模板测试:"
    local custom_pattern="[%level] %datetime | %module | %message | %script:%line"
    _formatter_plain_format "$test_event" "$custom_pattern"
    
    echo ""
    echo "4. 完整信息模板测试:"
    local full_pattern="%datetime [%level] [%trace_id] %module.%function - %message (%script:%line @%hostname)"
    _formatter_plain_format "$test_event" "$full_pattern"
}

# 如果直接执行此脚本,运行测试
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    _formatter_plain_test
fi

